import React,{useEffect} from 'react'
import { getItem } from '../api/home'
import { message } from 'antd';
import { usePartContext } from '../PartContext';
import Header from './Header';

const Home = (props) => {
	const {state,dispatch} = usePartContext();
	useEffect(()=>{
		getItem()
		.then(res=>{
			res.data.data.filter(item=>{
				item.isCollect=false;
				return item;
			})
			if(state.goods.length===0){
				dispatch({type:"getGoods",goods:res.data.data})
			}
		})
	},[])
	const collect = (good)=>{
		if(good.isCollect){
			message.info('您已收藏',0.5)
		}else{
			dispatch({type:"collect",good:good,id:good.id})
			message.success('收藏成功',0.5)
		}
	}
	return (
		<div className='home'>
			<Header history={props.history}/>
			<div className='goods-list'>
				{
					state.goods.map(item=>{
						return(
							<div key={item.id} className="goods">
								<img src={item.img}/>
								<p>{item.title}</p>
								<p>{item.price}</p>
								<button 
									onClick={()=>collect(item)}
								>
									{item.isCollect?"已收藏":"收藏"}
								</button>
							</div>
						)
					})
				}
			</div>
		</div>
	)
}

export default Home